package com.lastproject.web.bean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.lastproject.dto.AnswerDTO;
import com.lastproject.dto.QuestionOptionDTO;
import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.dao.AnswerDAORemote;
import com.lastproject.ejb.dao.QuestionOptionDAORemote;

@ManagedBean
@SessionScoped
public class QuestionOptionBean {
	
	@EJB
	QuestionOptionDAORemote questionOptionDAO;

	private QuestionOptionDTO questionOptionDTO;
	private List<AnswerDTO> list = new ArrayList<>();
	
	@ManagedProperty(value = "answerDTO")
	private AnswerDTO answerDTO; 
	
	public QuestionOptionDTO getQuestionOptionDTO() {
		return questionOptionDTO;
	}
	public void setQuestionOptionDTO(QuestionOptionDTO questionOptionDTO) {
		this.questionOptionDTO = questionOptionDTO;
	}
	
	public List<AnswerDTO> getList() {
		return list;
	}
	public void setList(List<AnswerDTO> list) {
		this.list = list;
	}

	public AnswerDTO getAnswerDTO() {
		return answerDTO;
	}
	public void setAnswerDTO(AnswerDTO answerDTO) {
		this.answerDTO = answerDTO;
	}
	
	/**
	 * Adds an answer to the database by sending an AnswerDTO object with the corresponding
	 * attribute values to the create() method in the AnswerDAORemote EJB
	 * @return 
	 * @param answer - String containing the personal answer of the user
	 * @param id - Integer containing the id of the question option for which the answer is addressed
	 */
	public void addAnswer(String answer, int id) {	
		answerDTO = new AnswerDTO();
		answerDTO.setPersonalAnswer(answer);
		answerDTO.setIdquestionOption(id);
		FacesContext f = FacesContext.getCurrentInstance();
		UserDTO userDTO = (UserDTO) f.getExternalContext().getSessionMap().get("userDTO");
		answerDTO.setIdUser(userDTO.getId());
		try {
			InitialContext ic = new InitialContext();
			AnswerDAORemote answerDAO = (AnswerDAORemote) ic.lookup("java:global/LastProjectEAR/LastProjectEJB/AnswerDAO!com.lastproject.ejb.dao.AnswerDAORemote");
			answerDAO.create(answerDTO);
		} catch (NamingException e) {
			System.out.println("Error!");
		}	
	}
	
	private String answer;
	public String getAnswer() {
		return answer;
	}

	public void setAnswer(String answer) {
		this.answer = answer;
	}
}
